package client.controller;

import client.Protocal.ClientSocket;
import common.EnvelopeMessage;
import common.bodies.LoginBody;
import common.bodies.RegisterBody;
import com.alibaba.fastjson.JSONObject;
import common.bodies.UserBody;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.TextField;
import javafx.scene.control.PasswordField;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;

import java.io.IOException;

public class LoginController {

    @FXML private TextField usernameField;
    @FXML private PasswordField passwordField;
    @FXML private TextField regUsernameField;
    @FXML private PasswordField regPasswordField;
    @FXML private TextField regName;

    private Stage primaryStage;
    @FXML private AnchorPane loginPane;
    @FXML private AnchorPane registerPane;
    private final ClientSocket client = new ClientSocket("localhost", 8080);

    // 设置主区域
    public void setPrimaryStage(Stage stage) {
        this.primaryStage = stage;
    }

    // 通用输入验证
    private boolean validateInput(String... inputs) {
        for (String input : inputs) {
            if (input == null || input.trim().isEmpty()) {
                return false;
            }
        }
        return true;
    }

    // 密码强度验证（至少6位）
    private boolean validatePassword(String password) {
        return password != null && password.length() >= 6;
    }

    // 显示错误提示
    private void showAlert(String title, String message) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }


    private void clearLoginForm() {
        usernameField.clear();
        passwordField.clear();
    }


    private void clearRegisterForm() {
        regUsernameField.clear();
        regPasswordField.clear();
        regName.clear();
    }

    @FXML
    public void onLogin() {
        String username = usernameField.getText();
        String password = passwordField.getText();

        if (!validateInput(username, password)) {
            showAlert("登录错误", "用户名和密码不能为空！");
            return;
        }

        if (!validatePassword(password)) {
            showAlert("密码错误", "密码长度不能少于6位！");
            return;
        }

        LoginBody body = new LoginBody(username, password);
        JSONObject jsonBody = (JSONObject) JSONObject.toJSON(body);
        EnvelopeMessage msg = new EnvelopeMessage("user", "login", jsonBody);
        client.send(msg);
    }

    @FXML
    public void onRegister() {
        String username = regUsernameField.getText();
        String password = regPasswordField.getText();
        String name = regName.getText();

        if (!validateInput(username, password, name)) {
            showAlert("注册错误", "所有字段都必须填写！");
            return;
        }

        if (!validatePassword(password)) {
            showAlert("密码错误", "密码长度不能少于6位！");
            return;
        }

        RegisterBody body = new RegisterBody(username, password, name);
        JSONObject jsonBody = (JSONObject) JSONObject.toJSON(body);
        EnvelopeMessage msg = new EnvelopeMessage("user", "register", jsonBody);
        client.send(msg);
    }

    @FXML
    public void initialize() {
        client.setMessageListener(msg -> {
            if ("user".equals(msg.getModule()) && "login_result".equals(msg.getAction())) {
                JSONObject body = msg.getBody();
                boolean success = body.getBoolean("success");
                String message = body.getString("message");
                UserBody user = body.getObject("user",UserBody.class);
                Platform.runLater(() -> {
                    if (success) {
                        System.out.println(message);
                        try {
                            FXMLLoader loader = new FXMLLoader(getClass().getResource("/client/ui/main.fxml"));
                            Parent root = loader.load();
                            MainController mainController = loader.getController();
                            mainController.setClientSocket(client);
                            mainController.setUser(user);
                            client.startHeartbeat();
                            Stage mainStage = new Stage();
                            mainStage.setScene(new Scene(root));
                            mainStage.setTitle("聊天室");
                            mainStage.show();
                            primaryStage.close();
                            mainController.loadFriendAndGroupList();
                        } catch (IOException e) {
                            e.printStackTrace();
                            showAlert("错误", "加载主界面失败");
                        }
                    } else {
                        showAlert("登录失败", message);
                    }
                });
            }

            if ("user".equals(msg.getModule()) && "register_result".equals(msg.getAction())) {
                JSONObject body = msg.getBody();
                boolean success = body.getBoolean("success");
                String message = body.getString("message");

                Platform.runLater(() -> {
                    if (success) {
                        showAlert("注册成功", message+"\n"+"即将跳转到登录页面");
                        new Thread(() -> {
                            try {
                                Thread.sleep(1000);
                                Platform.runLater(this::switchToLogin);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }).start();

                    } else {
                        showAlert("注册失败", message);
                    }
                });
            }
        });
    }

    @FXML
    public void switchToRegister() {
        clearLoginForm();
        loginPane.setVisible(false);
        registerPane.setVisible(true);
    }

    @FXML
    public void switchToLogin() {
        clearRegisterForm();
        registerPane.setVisible(false);
        loginPane.setVisible(true);
    }



}